import { Middleware, MiddlewareContext } from '../../core/types';

export type AuthType = 'bearer' | 'basic' | 'apiKey';

export interface AuthOptions {
  type?: AuthType;
  getToken?: (() => string) | string;
  onUnauthorized?: (error: any) => void;
}

export function auth(options: AuthOptions = {}): Middleware {
  const {
    type = 'bearer',
    getToken = () => localStorage.getItem('token') || '',
    onUnauthorized = (err) => console.error('Unauthorized:', err),
  } = options;

  return async (ctx: MiddlewareContext, next) => {
    const token = typeof getToken === 'function' ? getToken() : getToken;

    if (token) {
      ctx.config.headers = {
        ...ctx.config.headers,
      };

      switch (type) {
        case 'bearer':
          ctx.config.headers['Authorization'] = `Bearer ${token}`;
          break;
        case 'basic':
          ctx.config.headers['Authorization'] = `Basic ${token}`;
          break;
        case 'apiKey':
          ctx.config.headers['X-API-Key'] = token;
          break;
      }
    }

    try {
      await next();
    } catch (error) {
      ctx.error = error as any;
      if ((error as any)?.response?.status === 401) {
        onUnauthorized(error);
      }
      throw error;
    }
  };
}
